let gulp = require("gulp");

const rename = require('gulp-rename')
const postcss = require('gulp-postcss')
const pxtorpx = require('postcss-px2rpx')
const base64 = require('postcss-font-base64')
const combiner = require('stream-combiner2')


const sourcemaps = require('gulp-sourcemaps')
const jdists = require('gulp-jdists')
const through = require('through2')
const babel = require('gulp-babel')
const uglify = require('gulp-uglify')
const argv = require('minimist')(process.argv.slice(2))

const del = require('del')
const runSequence = require('run-sequence')

const src = './client'
const dist = './dist'
// 判断 gulp --type prod 命名 type 是否是生产打包
const isProd = argv.type === 'prod'

gulp.task('wxml', () => {
    return gulp
      .src(`${src}/**/*.wxml`)
      .pipe(gulp.dest(dist))
})

gulp.task('wxss', () => {
    const combined = combiner.obj([
        gulp.src(`${src}/**/*.{wxss,scss}`),
        sass().on('error', sass.logError),
        postcss([pxtorpx(), base64()]),
        rename((path) => (path.extname = '.wxss')),
        gulp.dest(dist)
    ])
    combined.on('error', handleError)
})

gulp.task('js', () => {
    gulp
      .src(`${src}/**/*.js`)
      .pipe(
          isProd ? jdists({trigger: 'prod'}) : jdists({trigger: 'dev'})
          )
        // 如果是 prod，则传入空的流处理方法，不生成 sourcemap
      .pipe(isProd ? through.obj() : sourcemaps.init())
      .pipe(
        babel({
          presets: ['env']
        })
      )
      // 如果是 prod，则使用 uglify 压缩 js
      .pipe(isProd ? uglify({compress: true }) : through.obj())
      .pipe(isProd ? through.obj() : sourcemaps.write('./'))
      .pipe(gulp.dest(dist))
})

gulp.task('json', () => {
    return gulp.src(`${src}/**/*.json`).pipe(gulp.dest(dist))
  })
gulp.task('images', () => {
    return gulp.src(`${src}/images/**`).pipe(gulp.dest(`${dist}/images`))
})
gulp.task('wxs', () => {
    return gulp.src(`${src}/**/*.wxs`).pipe(gulp.dest(dist))
})

gulp.task('watch', () => {
    ;['wxml', 'wxss', 'js', 'json', 'wxs'].forEach((v) => {
        gulp.watch(`${src}/**/*.${v}`, [v])
    })
    gulp.watch(`${src}/images/**`, ['images'])
    gulp.watch(`${src}/**/*.scss`, ['wxss'])
})

gulp.task('clean', () => {
    return del(['./dist/**'])
})


// 标注一个依赖，依赖的任务必须在这个任务开始之前被完成
// gulp.task('dev', ['clean'], function() {
//     // 现在任务 'one' 已经完成了
// });

// gulp.task('build', ['clean'], () => {
//     // gulp.series(['json', 'images', 'wxml', 'wxss', 'js', 'wxs'])
// })

// cloud-functions 处理方法
const cloudPath = './server/cloud-functions'
gulp.task('cloud', () => {
  return gulp
    .src(`${cloudPath}/**`)
    .pipe(isProd ? jdists({trigger: 'prod'}): jdists({trigger: 'dev'}))
    .pipe(gulp.dest(`${dist}/cloud-functions`))
})

gulp.task('watch:cloud', () => {
  gulp.watch(`${cloudPath}/**`, ['cloud'])
})

gulp.task('cloud:dev', () => {
  runSequence('cloud', 'watch:cloud')
})

